<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="goods">
      <!-- 标题栏 -->
      <detailNavbar />

      <detailSkeleton v-if="state.skeletonLoading" />
      
      <s-empty
        v-else-if="state.goodsInfo === null"
        text="商品不存在或已下架"
        icon="/static/soldout-empty.png"
        showAction
        actionText="再逛逛"
        actionUrl="/pages/goods/list"
      />
      
      <s-empty
        v-else-if="state.error"
        text="网络异常，请稍后重试"
        icon="/static/network-error.png"
        showAction
        actionText="重新加载"
        @actionClick="handleReload"
      />
      
      <block v-else>
        <view class="detail-swiper-selector">
          <view class="swiper-container">
            <swiper 
              class="goods-swiper" 
              :indicator-dots="true" 
              :autoplay="false" 
              :interval="3000" 
              :duration="500"
            >
              <swiper-item v-for="(item, index) in state.goodsSwiper" :key="index">
                <image 
                  class="swiper-image" 
                  :src="item.src" 
                  mode="aspectFill"
                />
              </swiper-item>
            </swiper>
          </view>
          
          <view class="title-card detail-card">
            <view class="product-main">
              <view class="price-section">
                <view class="current-price">
                  <text class="price-symbol">￥</text>
                  <text class="price-value">{{ currentPrice }}</text>
                  <text class="price-unit">{{ state.goodsInfo.product.unit }}</text>
                </view>
                <view class="price-info">
                  <view 
                    class="original-price" 
                    v-if="isVipUser && state.goodsInfo.product.price2 > 0"
                  >
                    原价 ￥{{ state.goodsInfo.product.price }}
                  </view>
                </view>
              </view>
              
              <view class="stock-info">
                <text class="stock-label">库存</text>
                <text class="stock-value">{{ state.goodsInfo.totalStock }}</text>
              </view>
            </view>
            
            <view class="product-title">{{ state.goodsInfo.product.name }}</view>
            
            <view class="product-brand" v-if="state.goodsInfo.product.brandName">
              <text class="brand-label">品牌：</text>
              <text class="brand-name">{{ state.goodsInfo.product.brandName }}</text>
              <text class="category-name" v-if="state.goodsInfo.product.productCategoryName">
                · {{ state.goodsInfo.product.productCategoryName }}
              </text>
            </view>
            
            <view class="discounts-box" v-if="state.goodsInfo.promos && state.goodsInfo.promos.length">
              <view class="discount-tags">
                <view
                  class="discount-tag"
                  v-for="promo in state.goodsInfo.promos"
                  :key="promo.id"
                  @tap="onActivity"
                >
                  {{ promo.title }}
                </view>
              </view>
            </view>
          </view>

          <view class="detail-cell-card detail-card">
            <detail-cell-sku
              v-model="state.selectedSkuPrice.spData"
              :skus="state.goodsInfo.skus || []"
              @tap="state.showSelectSku = true"
            />
          </view>

          <s-select-sku
            :goodsInfo="state.goodsInfo"
            :show="state.showSelectSku"
            @addCart="onAddCart"
            @buy="onBuy"
            @change="onSkuChange"
            @close="state.showSelectSku = false"
          />
        </view>
        
        <detail-content-card 
          class="detail-content-selector" 
          :content="state.goodsInfo.product && state.goodsInfo.product.detailMobileHtml ? state.goodsInfo.product.detailMobileHtml : state.goodsInfo.product && state.goodsInfo.product.detailHtml ? state.goodsInfo.product.detailHtml : ''"
        />
        
        <view class="bottom-safe-area"></view>
        
        <detail-tabbar v-model="state.goodsInfo">
          <view 
            class="buy-box" 
            v-if="state.goodsInfo.totalStock > 0"
          >
            <button
              class="add-btn"
              @tap="onAddCartClick"
              :disabled="state.isAddingCart"
            >
              <text v-if="state.isAddingCart">添加中...</text>
              <text v-else>加入购物车</text>
            </button>
            <button
              class="buy-btn"
              @tap="onBuyClick"
              :disabled="state.isBuying"
            >
              <text v-if="state.isBuying">处理中...</text>
              <text v-else>立即购买</text>
            </button>
          </view>
          <view class="buy-box" v-else>
            <button class="disabled-btn" disabled>
              已售罄
            </button>
          </view>
        </detail-tabbar>
        
        <s-coupon-get
          v-model="state.couponInfo"
          :show="state.showModel"
          @close="state.showModel = false"
          @get="onGetCoupon"
        />
        
        <s-activity-pop
          v-model="state.activityInfo"
          :show="state.showActivityModel"
          @close="state.showActivityModel = false"
        />
      </block>
    </s-layout>
  </view>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import detailNavbar from './components/detail/detail-navbar.vue';
  import detailCellSku from './components/detail/detail-cell-sku.vue';
  import detailTabbar from './components/detail/detail-tabbar.vue';
  import detailSkeleton from './components/detail/detail-skeleton.vue';
  import detailContentCard from './components/detail/detail-content-card.vue';
  import { isEmpty } from 'lodash';

  const userInfo = computed(() => sheep.$store('user').userInfo);
  const isVipUser = computed(() => userInfo.value.level > 0);

  onPageScroll(() => {});

  onPullDownRefresh(() => {
    handleReload();
  });

  const state = reactive({
    goodsId: 0,
    skeletonLoading: true,
    goodsInfo: {},
    showSelectSku: false,
    goodsSwiper: [],
    selectedSkuPrice: {
      price: 0,
      price2: 0,
      originalPrice: 0,
      stock: 0,
      spData: '{}'
    },
    showModel: false,
    couponInfo: [],
    showActivityModel: false,
    activityInfo: [],
    error: false,
    isAddingCart: false,
    isBuying: false,
  });

  const currentPrice = computed(() => {
    if (isVipUser.value && state.goodsInfo.product && state.goodsInfo.product.price2 > 0) {
      return state.goodsInfo.product.price2;
    }
    return (state.goodsInfo.product && state.goodsInfo.product.price) || 0;
  });

  function onSkuChange(e) {
    state.selectedSkuPrice = e;
  }

  function onAddCartClick() {
    if (state.goodsInfo.skus && state.goodsInfo.skus.length > 1) {
      state.showSelectSku = true;
    } else {
      const skuData = {
        productId: state.goodsInfo.product.id,
        id: state.goodsInfo.skus[0].id,
        buyNum: 1
      };
      onAddCart(skuData);
    }
  }

  function onBuyClick() {
    if (state.goodsInfo.skus && state.goodsInfo.skus.length > 1) {
      state.showSelectSku = true;
    } else {
      const skuData = {
        productId: state.goodsInfo.product.id,
        id: state.goodsInfo.skus[0].id,
        buyNum: 1
      };
      onBuy(skuData);
    }
  }

  async function onAddCart(e) {
    if (state.isAddingCart) return;
    
    state.isAddingCart = true;
    try {
      await sheep.$store('cart').add(e);
      state.showSelectSku = false;
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
    } catch (error) {
      uni.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    } finally {
      state.isAddingCart = false;
    }
  }

  async function onBuy(e) {
    if (state.isBuying) return;
    
    state.isBuying = true;
    try {
      await sheep.$router.go('/pages/order/confirm', {
        data: JSON.stringify({
          order_type: 'goods',
          goods_list: [{
            goods_id: e.productId,
            goods_num: e.buyNum,
            skuId: e.id
          }],
        }),
      });
      state.showSelectSku = false;
    } catch (error) {
      uni.showToast({
        title: '购买失败，请重试',
        icon: 'none'
      });
    } finally {
      state.isBuying = false;
    }
  }

  function onActivity() {
    state.activityInfo = state.goodsInfo.promos;
    state.showActivityModel = true;
  }

  async function onGetCoupon(id) {
    try {
      const { error, msg } = await sheep.$api.coupon.get(id);
      if (error === 0) {
        uni.showToast({
          title: msg || '领取成功',
          icon: 'success'
        });
        setTimeout(() => {
          loadCoupons();
        }, 1000);
      } else {
        uni.showToast({
          title: msg || '领取失败',
          icon: 'none'
        });
      }
    } catch (error) {
      uni.showToast({
        title: '领取失败，请重试',
        icon: 'none'
      });
    }
  }

  async function loadCoupons() {
    try {
      const { error, data } = await sheep.$api.coupon.listByGoods(state.goodsId);
      if (error === 0) {
        state.couponInfo = data || [];
      }
    } catch (error) {
      
    }
  }

  async function handleReload() {
    state.error = false;
    state.skeletonLoading = true;
    await loadGoodsDetail();
    uni.stopPullDownRefresh();
  }

  async function loadGoodsDetail() {
    try {
      const res = await sheep.$api.goods.detail(state.goodsId);
      
      if (!res || !res.product) {
        state.goodsInfo = null;
        return;
      }
      
      state.goodsInfo = res;
      
      if (res.product.albumPics) {
        const albumPics = res.product.albumPics.split(',').filter(pic => pic.trim());
        if (albumPics.length > 0) {
          state.goodsSwiper = albumPics.map(pic => ({
            src: pic.trim(),
            type: 'image'
          }));
        } else if (res.product.pic) {
          state.goodsSwiper = [{
            src: res.product.pic,
            type: 'image'
          }];
        }
      } else if (res.product.pic) {
        state.goodsSwiper = [{
          src: res.product.pic,
          type: 'image'
        }];
      }
      
      if (!state.goodsSwiper || state.goodsSwiper.length === 0) {
        state.goodsSwiper = [{
          src: '/static/goods-empty.png',
          type: 'image'
        }];
      }
      
      let totalStock = 0;
      if (res.skus && res.skus.length > 0) {
        res.skus.forEach(sku => {
          totalStock += sku.stock || 0;
        });
        
        state.selectedSkuPrice = {
          price: res.skus[0].price,
          price2: res.skus[0].price2,
          originalPrice: res.product.originalPrice || res.skus[0].originalPrice,
          stock: res.skus[0].stock,
          spData: res.skus[0].spData || '{}'
        };
      } else {
        state.selectedSkuPrice = {
          price: res.product.price,
          price2: res.product.price2,
          originalPrice: res.product.originalPrice,
          stock: totalStock,
          spData: '{}'
        };
      }
      
      state.goodsInfo.totalStock = totalStock;
      
    } catch (error) {
      state.error = true;
      uni.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      state.skeletonLoading = false;
    }
  }

  const shareInfo = computed(() => {
    if (isEmpty(state.goodsInfo) || !state.goodsInfo.product) return {};
    
    const subtitle = [state.goodsInfo.product.brandName, state.goodsInfo.product.productCategoryName]
      .filter(Boolean).join(' · ') || state.goodsInfo.product.name;
    
    return sheep.$platform.share.getShareInfo(
      {
        title: state.goodsInfo.product.name,
        image: sheep.$url.cdn(state.goodsInfo.product.pic),
        desc: subtitle,
        params: {
          page: '2',
          query: state.goodsInfo.product.id,
        },
      },
      {
        type: 'goods',
        title: state.goodsInfo.product.name,
        image: sheep.$url.cdn(state.goodsInfo.product.pic),
        price: state.goodsInfo.product.price,
        original_price: state.goodsInfo.product.originalPrice,
      },
    );
  });

  onLoad(async (options) => {
    if (!options.id) {
      state.goodsInfo = null;
      state.skeletonLoading = false;
      return;
    }
    
    state.goodsId = options.id;
    await loadGoodsDetail();
  });
</script>

<style lang="scss" scoped>
  .detail-card {
    background-color: #fff;
    margin: 0 20rpx 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
  }

  .swiper-container {
    .goods-swiper {
      height: 700rpx;
      
      .swiper-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .title-card {
    padding: 30rpx;
    margin-top: 0;
    
    .product-main {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20rpx;
    }
    
    .price-section {
      flex: 1;
      
      .current-price {
        display: flex;
        align-items: baseline;
        margin-bottom: 8rpx;
        
        .price-symbol {
          font-size: 28rpx;
          color: #ff3000;
          font-weight: 500;
        }
        
        .price-value {
          font-size: 48rpx;
          color: #ff3000;
          font-weight: 600;
          font-family: 'DIN Alternate', 'Helvetica Neue', sans-serif;
        }
        
        .price-unit {
          font-size: 24rpx;
          color: #666;
          margin-left: 8rpx;
        }
      }
      
      .price-info {
        display: flex;
        gap: 16rpx;
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
      }
    }
    
    .stock-info {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      
      .stock-label {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 4rpx;
      }
      
      .stock-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
    
    .product-title {
      font-size: 32rpx;
      font-weight: 600;
      line-height: 1.4;
      color: #333;
      margin-bottom: 16rpx;
    }
    
    .product-brand {
      font-size: 26rpx;
      color: #666;
      margin-bottom: 20rpx;
      
      .brand-label {
        color: #999;
      }
      
      .brand-name {
        color: #333;
        font-weight: 500;
      }
      
      .category-name {
        color: #666;
      }
    }
    
    .discounts-box {
      .discount-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;
      }
      
      .discount-tag {
        padding: 8rpx 16rpx;
        font-size: 24rpx;
        font-weight: 500;
        border-radius: 8rpx;
        color: var(--ui-BG-Main);
        background: var(--ui-BG-Main-tag);
        border: 1rpx solid var(--ui-BG-Main);
      }
    }
  }

  .detail-cell-card {
    padding: 0;
  }

  .bottom-safe-area {
    height: 160rpx;
    width: 100%;
  }

  .buy-box {
    display: flex;
    padding: 0 20rpx;
    gap: 20rpx;
    
    .add-btn {
      flex: 1;
      height: 80rpx;
      font-weight: 500;
      font-size: 30rpx;
      border-radius: 40rpx;
      background-color: var(--ui-BG-Main-light);
      color: var(--ui-BG-Main);
      border: 2rpx solid var(--ui-BG-Main);
      transition: all 0.3s ease;
      
      &:disabled {
        opacity: 0.6;
      }
    }

    .buy-btn {
      flex: 1;
      height: 80rpx;
      font-weight: 500;
      font-size: 30rpx;
      border-radius: 40rpx;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: #fff;
      transition: all 0.3s ease;
      
      &:disabled {
        opacity: 0.6;
      }
    }
    
    .disabled-btn {
      width: 100%;
      height: 80rpx;
      border-radius: 40rpx;
      background: #ccc;
      color: #fff;
      font-size: 30rpx;
    }
  }
</style>
